import redPacket from "../assets/images/red_packet/icon1.jpg";
import {random, sample} from "lodash";

export default class RedPacketMiddle {
  constructor(options) {
    //类型 奇数:红包 偶数:礼物
    this.type = options.type || 1;
    //红包图片地址
    this.url = options.url || redPacket;
    // 礼物图片地址
    this.giftUrl = options.giftUrl || redPacket;
    //红包宽度
    this.width = options.width || "5vw";
    //红包高度
    this.height = options.height || "auto";
    //红包的轨道
    this.track =
      options.track ||
      sample([
        0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85,
        90, 95, 100,
      ]);
    //红包旋转角度
    this.angle = options.angle || random(-360, 360);
    // 红包掉落速度
    this.speed = options.speed || random(2, 4);
    //红包回调,
    this.callback = options.callback;
    //红包放入那个容器
    this.parent = options.parent || document.body;
    //创建红包
    this.create();
  }

  //创建方法
  create() {
    //创建一个红包dom元素
    const img = document.createElement("img");
    //图片地址
    if (this.type % 2 === 0) {
      //偶数:礼物
      img.src = this.giftUrl;
    } else {
      //奇数:红包
      img.src = this.url;
    }
    //图片宽度
    img.style.width = this.width;
    //图片高度
    img.style.height = this.height;
    //开启定位
    img.style.position = "absolute";
    //红包轨道
    img.style.left = this.track + "vw";
    img.animate(
      [
        {transform: "translateY(10vh)  rotateY(0) rotateX(0) translateX(0)"},
        {
          transform: `translateY(110vh)  rotateY(${this.angle}deg)   rotateX(${this.angle}deg)  translateX(15vw)`,
        },
      ],
      {
        duration: this.speed * 1000,
        fill: "forwards",
        easing: "cubic-bezier(0.42, 0, 0.58, 1)", // 使用贝塞尔函数
      }
    );
    // 图片的回调
    img.ontouchstart = this.destroy.bind(this, img);
    //放入容器
    this.parent.appendChild(img);
    setTimeout(() => {
      // @ts-ignore
      img.remove();
    }, this.speed * 1000);
  }

  //图片销毁方法
  destroy(currentImg) {
    // @ts-ignore
    currentImg.remove();
    if (this.type % 2 === 0) {
      //偶数:礼物
      this.callback(2);
    } else {
      //奇数:红包
      this.callback(1);
    }
  }
}
